//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import tv.dyndns.kishibe.client.constant.Constant;
import tv.dyndns.kishibe.client.game.SceneGame;
import tv.dyndns.kishibe.client.packet.PacketMatchingData;
import tv.dyndns.kishibe.client.packet.PacketMatchingPlayer;
import tv.dyndns.kishibe.client.packet.PacketProblem;
import tv.dyndns.kishibe.client.packet.PacketReadyForGame;

import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.widgetideas.graphics.client.ImageLoader;

public class SceneReadyForGame extends SceneBase {
	private static final Logger logger = Logger.getLogger(SceneReadyForGame.class.getName());
	private static final int MAX_RETRY_COUNT = 3;
	private static final int TIMER_INTERVAL = 1000;
	private final PanelReadyForGame panel = new PanelReadyForGame();
	private List<PacketProblem> problems;
	private List<PacketMatchingPlayer> players;
	private boolean transited = false;
	private final StatusUpdater<PacketReadyForGame> updater = new StatusUpdater<PacketReadyForGame>(
			PacketReadyForGame.class.getName() + ":" + SharedData.get().getSessionId(),
			TIMER_INTERVAL) {
		@Override
		protected void request(AsyncCallback<PacketReadyForGame> callback) {
			int sessionId = SharedData.get().getSessionId();
			Service.Util.getInstance().waitForGame(sessionId, callback);
		}

		@Override
		protected PacketReadyForGame parse(String json) {
			return PacketReadyForGame.Json.READER.read(json);
		}

		@Override
		protected void onReceived(PacketReadyForGame status) {
			callbackWaitForGame.onSuccess(status);
		}
	};
	private final boolean addPenalty;
	private int retryCount = 0;

	public SceneReadyForGame(boolean addPenalty) {
		this.addPenalty = addPenalty;
		Controller.getInstance().setGamePanel(panel);

		SoundPlayer.getInstance().play(Constant.SOUND_URL_READY_FOR_GAME);
	}

	private final AsyncCallback<PacketReadyForGame> callbackWaitForGame = new AsyncCallback<PacketReadyForGame>() {
		@Override
		public void onSuccess(PacketReadyForGame result) {
			if (transited) {
				return;
			}

			if (panel == null) {
				return;
			}

			int restSeconds = result.restSeconds;
			if (restSeconds > 0) {
				panel.setRestSecond(restSeconds);
				return;
			}

			// ゲーム画面へ移行する
			if (problems == null) {
				logger.log(Level.SEVERE, "問題の取得に失敗しました。F5を押してリロードしてください。");
				updater.stop();
				return;
			}

			if (players == null) {
				logger.log(Level.SEVERE, "プレイヤー情報の取得に失敗しました。F5を押してリロードしてください");
				updater.stop();
				return;
			}

			transited = true;
			Controller.getInstance().setScene(new SceneGame(problems, players, addPenalty));
			updater.stop();
		}

		@Override
		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "待機状態の取得中にエラーが発生しました", caught);
		}
	};

	/**
	 * 問題を取得する
	 */
	private void recieveProblem() {
		final int sessionId = SharedData.get().getSessionId();
		Service.Util.getInstance().getProblem(sessionId, callbackRecieveProblem);
	}

	private final Timer timerRecieveProblem = new Timer() {
		@Override
		public void run() {
			recieveProblem();
		}
	};
	private final AsyncCallback<List<PacketProblem>> callbackRecieveProblem = new AsyncCallback<List<PacketProblem>>() {
		@Override
		public void onSuccess(List<PacketProblem> result) {
			if (result == null) {
				timerRecieveProblem.schedule(Constant.RETRY_DELAY);
				return;
			}

			problems = result;
			recievePlayerData();

			// 1問目の画像の事前読み込みを行う
			ImageLoader.loadImages(result.get(0).getResizedImageUrls().toArray(new String[0]),
					new ImageLoader.CallBack() {
						@Override
						public void onImagesLoaded(ImageElement[] imageElements) {
						}
					});
		}

		@Override
		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "問題の取得中にエラーが発生しました。パケットを再送します。", caught);
			timerRecieveProblem.schedule(Constant.RETRY_DELAY);
		}
	};

	/**
	 * プレイヤー一覧を取得する
	 */
	private void recievePlayerData() {
		final int sessionId = SharedData.get().getSessionId();
		Service.Util.getInstance().getMatchingData(sessionId, callbackGetMatchingData);
	}

	private final Timer timerRecievePlayerdata = new Timer() {
		@Override
		public void run() {
			recievePlayerData();
		}
	};

	private final AsyncCallback<PacketMatchingData> callbackGetMatchingData = new AsyncCallback<PacketMatchingData>() {
		@Override
		public void onSuccess(PacketMatchingData result) {
			if (result == null || result.players == null) {
				timerRecievePlayerdata.schedule(Constant.RETRY_DELAY);
				return;
			}

			players = result.players;
			panel.setPlayerList(players);
		}

		@Override
		public void onFailure(Throwable caught) {
			if (++retryCount > MAX_RETRY_COUNT) {
				logger.log(Level.SEVERE, "プレイヤーリストの取得にエラーが発生しました。ページを再読み込みして下さい", caught);
				updater.stop();
				return;
			}

			logger.log(Level.WARNING, "プレイヤーリストの取得にエラーが発生しました。パケットを再送します。", caught);
			timerRecievePlayerdata.schedule(Constant.RETRY_DELAY);
		}
	};

	@Override
	protected void onLoad() {
		super.onLoad();
		new Timer() {
			@Override
			public void run() {
				// 問題取得　-> プレイヤー一覧取得の順に行う
				recieveProblem();
			}
		}.schedule(1 * 1000);
		updater.start();
	}

	@Override
	protected void onUnload() {
		updater.stop();
		super.onUnload();
	}
}
